/** @file log.c 
 * Implementiert das Logging für das Host- und Zielsystem
 * 
 * @author Daniel Kummer, Sebastian Kummer
 * @date Donnerstag, Dezember 12, 2007
 * @version 1.0
 */

#include <stdio.h>
#include <time.h>
#include <string.h>
#include "lcv-config.h"
#include "log.h"

void lcv_first_log_entry();

/*
 * Logging aktivieren, deaktivieren
 */
unsigned char logging_is_enabled = TRUE;

/*
 * Neue Logdatei
 */
unsigned char first_log_entry = TRUE;

void lcv_logging(const unsigned char enable)
{
	logging_is_enabled = enable;
}

void lcv_log(const char * entry)
{
	if (logging_is_enabled) {
		if (first_log_entry) {
			lcv_first_log_entry();
			first_log_entry = FALSE;
		}
		
		unsigned int buffersize = 256;
		char t_buffer[buffersize];
		time_t curtime;
		struct tm *loctime;
			     
		/* Momentane Zeit holen */
		curtime = time (NULL);
			     
		/* Konvertieren zur Lokalzeit */
		loctime = localtime (&curtime);
			    
		/* Format ändern */
		strftime (t_buffer, buffersize, "%Y-%m-%d %H:%M:%S", loctime);	
		
		/* Newlines des Eintrages löschen */	
		char corrected_entry[256]; 
		strcpy(corrected_entry, entry);	
		char * newline;
		
		while ((newline = strchr(corrected_entry, '\n')) != NULL) {
			(*newline)	= ' ';
		}
									
		FILE* logfile = fopen(LOG_FILE_NAME, "a");		 
		fprintf(logfile, "%s - %s\n", t_buffer, corrected_entry);
		fclose(logfile);
	}
}

void lcv_first_log_entry()
{
	if (first_log_entry) {
		FILE* logfile = fopen(LOG_FILE_NAME, "a");		 
		fprintf(logfile, "/***************************************************************\n");
		fprintf(logfile, "* NEW PROGRAMM EXECUTION\n");
		fprintf(logfile, "***************************************************************/\n");
		fclose(logfile);
		
		first_log_entry = FALSE;
	}
}

void lcv_log_error(const char * entry, const char* function)
{		
	char buffer[256];
	sprintf(buffer, "Error in Function >%s<: %s", function, entry);	
	lcv_log(buffer);
}

void lcv_log_warning(const char* entry, const char* function)
{
	char buffer[256];
	sprintf(buffer, "Warning in Function >%s<: %s", function, entry);	
	lcv_log(buffer);
}
